package com.piece.core.verifycode.factory.sms;

import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.verifycode.factory.ValidateCode;
import com.piece.core.verifycode.factory.ValidateCodeGenerator;
import com.piece.core.verifycode.properties.VerifyCodeProperties;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 短信验证码生成器
 */
@Component("smsValidateCodeGenerator")
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private VerifyCodeProperties verifyCodeProperties;

    @Override
    public ValidateCode generate(HttpServletRequest request, HttpServletResponse response) {
        int length = Convert.toInt(verifyCodeProperties.getSmsLength(), 4);
        length = Convert.toInt(applicationProperties.getValue(ApplicationConstants.SMS_KAPTCHA_LENGTH), length);
        String code = RandomStringUtils.randomNumeric(length);
        return new ValidateCode(code, verifyCodeProperties.getSmsExpire());
    }
}
